import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.File;


public class ResponseAction {

    RequestAction request;
    OutputStream output;

    public ResponseAction(OutputStream output) {
	this.output = output;
    }
    
    public void setRequest(RequestAction request) {
	this.request = request;
    }

    public void send() throws IOException {
	byte[] bytes = new byte[1024];
	FileInputStream fis = null;
	try {
	    File file = new File(HttpServer.WEB_ROOT, request.getURI());
	    System.out.println(file.getName());
	    if(file.exists()) {
    	
		fis = new FileInputStream(file);
		int ch = fis.read(bytes, 0, 1024);
		while (ch!=-1) {
		    output.write(bytes, 0, ch);
		    ch = fis.read(bytes, 0, 1024);
		}
	    }
	    else {
		String html = 
		    "HTTP/1.0 \r\n"
		    + "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
		    + "<HTML>\r\n"
		    + "<HEAD>\r\n"
		    + "<TITLE>BLA BLA</TITLE>\r\n" 
		    + "</HEAD>"
		    + "<BODY>HUHU\r\n"
		    + "</BODY>" + "" 
		    + "</HTML>\r\n";
		output.write(html.getBytes());
	    }
	}
	catch (Exception e) {
	    System.out.println(e.toString() );
	}
	finally {
	    if (fis!=null)
		fis.close();
	}
    }
    
    private String getContentType(File f) {
    	String fileExtension = f.getName().split(".")[1]; 
	    String content = "";
	    if (fileExtension == "htm"  ||
	    	fileExtension == "html" || 
	    	fileExtension == "txt") 
	    	content = "text/html";
	    
	    if (fileExtension == "jpg"  || 
	    	fileExtension == "jpeg")
	    	content = "image/jpeg";
	    
	    if (fileExtension == "png")
	    	content = "image/png";
	    
	    if (fileExtension == "gif")
	    	content = "image/gif";
	    
	    return "Content-Type: " + content + ";\r\n";	
    }
}
